package com.xijia.wuyouwallet.fragment;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.xijia.wuyouwallet.MyApp;
import com.xijia.wuyouwallet.R;
import com.xijia.wuyouwallet.activity.AttestationActivity;
import com.xijia.wuyouwallet.activity.CommonFwvActivity;
import com.xijia.wuyouwallet.activity.CommonWvActivity;
import com.xijia.wuyouwallet.activity.CreditcardRefundACtivity;
import com.xijia.wuyouwallet.activity.DitchActivity;
import com.xijia.wuyouwallet.activity.ManagePsdActivity;
import com.xijia.wuyouwallet.activity.MeWalletActivity;
import com.xijia.wuyouwallet.activity.PersonInfoActivity;
import com.xijia.wuyouwallet.activity.TradeBillActivity;
import com.xijia.wuyouwallet.activity.UpgradeNewActivity;
import com.xijia.wuyouwallet.adapter.PicassoImgLoader;
import com.xijia.wuyouwallet.api.MyCallBack;
import com.xijia.wuyouwallet.base.BaseFragment;
import com.xijia.wuyouwallet.bean.NoticeData;
import com.xijia.wuyouwallet.utils.MyLogger;
import com.xijia.wuyouwallet.utils.UrlConfig;
import com.xijia.wuyouwallet.utils.XUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/7/11 0011.
 */

public class ReceiptFragment extends BaseFragment implements OnBannerClickListener,View.OnClickListener{

    private Banner receipt_banner;
    private HorizontalScrollView receipt_scroll;
    private LinearLayout receipt_llconver;
    private MyHandler roolHandler;
    private Timer timer;
    private MyTask task;
    private static final int SPEED = 30;
    private int moveSpeed = 2;
    private int moveSum = 0;
    private int lineWidth = 0;
    private int lineHeight = 0;
    private int moveEnd = 0;
    private static final int MSG_TEXTVIEW_REGRESH = 2;

    private List<NoticeData.DataBean> noticeList;


    private AlertDialog operationDialog;


    //新增加控件
    private  LinearLayout receipt_quickPay,receipt_scanCodePay,
            receipt_wallet,receipt_profit,receipt_rate,receipt_bill
            ,receipt_team,receipt_up;
    private ImageView receipt_message;


    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
               /* case MSG_BANNER_REGRESH:
                    int curBanner = home_vp.getCurrentItem();
                    home_vp.setCurrentItem(curBanner + 1);
                    if (curBanner == blist.size() - 1) {
                        home_vp.setCurrentItem(0);
                    }

                    break;*/
                case MSG_TEXTVIEW_REGRESH:
                    receipt_llconver.layout(moveSum, 0, moveSum + lineWidth, lineHeight);
                    break;
                default:
                    break;
            }
        };
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_receipt,null);
        initView(view);
        return view;
    }
    private void initView(View view){
        receipt_banner = (Banner) view.findViewById(R.id.receipt_banner);
        receipt_scroll = (HorizontalScrollView) view.findViewById(R.id.receipt_scroll);
        receipt_llconver = (LinearLayout) view.findViewById(R.id.receipt_llconver);
        //新增加控件
        receipt_quickPay = (LinearLayout) view.findViewById(R.id.receipt_quickPay);
        receipt_quickPay.setOnClickListener(this);
        receipt_scanCodePay = (LinearLayout) view.findViewById(R.id.receipt_scanCodePay);
        receipt_scanCodePay.setOnClickListener(this);
        receipt_wallet = (LinearLayout) view.findViewById(R.id.receipt_wallet);
        receipt_wallet.setOnClickListener(this);
        receipt_profit = (LinearLayout) view.findViewById(R.id.receipt_profit);
        receipt_profit.setOnClickListener(this);
        receipt_rate = (LinearLayout) view.findViewById(R.id.receipt_rate);
        receipt_rate.setOnClickListener(this);
        receipt_bill = (LinearLayout) view.findViewById(R.id.receipt_bill);
        receipt_bill.setOnClickListener(this);
        receipt_team = (LinearLayout) view.findViewById(R.id.receipt_team);
        receipt_team.setOnClickListener(this);
        receipt_up = (LinearLayout) view.findViewById(R.id.receipt_up);
        receipt_up.setOnClickListener(this);
        receipt_message = (ImageView) view.findViewById(R.id.receipt_message);
        receipt_message.setOnClickListener(this);
        List<Integer> list = new ArrayList<>();
        list.add(R.mipmap.banner01);
        list.add(R.mipmap.banner02);
        receipt_banner.setImages(list).setBannerAnimation(Transformer.BackgroundToForeground).setImageLoader(new PicassoImgLoader())
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR).setIndicatorGravity(BannerConfig.RIGHT).setDelayTime(4000)
                .setOnBannerClickListener(ReceiptFragment.this).start();
        initData();
        if (MyApp.userData.getData().getCertification_state().equals("0")){
            initOperationDialog(2);
        }
    }

    //绑定微信提示对话框
    private void initOperationDialog(final int hitType) {
        operationDialog=new AlertDialog.Builder(getActivity()).create();
        //点击外部区域不能取消dialog
        operationDialog.setCanceledOnTouchOutside(false);
        //dialog.setOnKeyListener(keylistener);
        operationDialog.show();

        Window window = operationDialog.getWindow();
        window.setContentView(R.layout.dialog_operation);
        window.getDecorView().setBackgroundColor(Color.TRANSPARENT);


        //View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_operation, null);
        TextView dialog_binding_sure = (TextView) window.findViewById(R.id.dialog_binding_sure);
        TextView dialog_binding_cancle = (TextView) window.findViewById(R.id.dialog_binding_cancle);
        //TextView dialog_binding_title = (TextView) view.findViewById(R.id.dialog_binding_title);
        TextView dialog_binding_content = (TextView) window.findViewById(R.id.dialog_binding_content);
        if (hitType==1){
            dialog_binding_content.setText("您即将进入的模块为会员收费模块，需付费开通，如需开通请点击立即前往");
        }else if (hitType==2){
            dialog_binding_content.setText("您尚未实名认证");
            dialog_binding_cancle.setText("下次完善");
        }
        dialog_binding_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                operationDialog.dismiss();
            }
        });
        dialog_binding_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                operationDialog.dismiss();
                if (hitType==1){
                    jumpToPage(UpgradeNewActivity.class);
                }else if (hitType==2){
                    jumpToPage(AttestationActivity.class);
                }
            }
        });
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);
    }

    /**
     * 获取数据
     */
    private void initData(){
        XUtil.Post(UrlConfig.GET_NOTICE_URL,null,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //MyLogger.wLog().e("获取公告result="+result);
                NoticeData noticeData = JSONObject.parseObject(result,NoticeData.class);
                if (noticeData.getCode()==200){
                    noticeList = noticeData.getData();
                    showRollNews();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                MyLogger.wLog().e("获取公告失败"+ex.toString());
            }
        });
    }
    @Override
    public void onClick(View view) {
        Bundle bundle = null;
        switch (view.getId()){
            //新增肌按钮
            case R.id.receipt_quickPay://快捷支付
                if (MyApp.userData.getData().getCertification_state().equals("0")){
                    initOperationDialog(2);
                    return;
                }
                if (MyApp.userData.getData().getRole_id().equals("1")){
                    initOperationDialog(1);
                    return;
                }
                //jumpToPage(ReceiptMoneyActivity.class);
                jumpToPage(DitchActivity.class);
                break;
            case R.id.receipt_scanCodePay://信用卡还款
                //showToast("维护中");
                if (MyApp.userData.getData().getCertification_state().equals("0")){
                    initOperationDialog(2);
                    return;
                }
                jumpToPage(CreditcardRefundACtivity.class);
                break;
            case R.id.receipt_wallet://我的钱包
                if (MyApp.userData.getData().getCertification_state().equals("0")){
                    initOperationDialog(2);
                    return;
                }
                /*if (MyApp.userData.getData().getRole_id().equals("3")){
                    initOperationDialog(1);
                    return;
                }*/
                jumpToPage(MeWalletActivity.class);
                break;
            case R.id.receipt_profit://我的盈利
                bundle = new Bundle();
                bundle.putString("url", UrlConfig.ME_PROFIT+"/id/"+MyApp.userData.getData().getUser_id());
                bundle.putString("title","我的盈利");
                jumpToPage(CommonFwvActivity.class,bundle);
                break;
            case R.id.receipt_rate://我的费率
                bundle = new Bundle();
                bundle.putString("url", UrlConfig.SETTLE_RATE_URL);
                bundle.putString("title","结算费率");
                jumpToPage(CommonWvActivity.class,bundle);
                break;
            case R.id.receipt_bill://交易账单
                jumpToPage(TradeBillActivity.class);
                break;
            case R.id.receipt_team://我的团队
                bundle = new Bundle();
                bundle.putString("url", UrlConfig.ME_TEAM+"/id/"+MyApp.userData.getData().getUser_id());
                bundle.putString("title","我的商户");
                jumpToPage(CommonFwvActivity.class,bundle);
                break;
            case R.id.receipt_up://我要升级
                if (MyApp.userData.getData().getCertification_state().equals("0")){
                    initOperationDialog(2);
                    return;
                }
                jumpToPage(UpgradeNewActivity.class);
                break;
            case R.id.receipt_message://消息
                break;
        }
    }
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            receipt_llconver.layout(moveSum, 0, moveSum + lineWidth, lineHeight);
        }
    }
    //横向移动textview实现
    private void showRollNews() {
        setView(receipt_llconver);
        if (roolHandler == null) {
            roolHandler = new MyHandler();
        }
        receipt_llconver.measure(receipt_llconver.getMeasuredWidth(), receipt_llconver.getMeasuredHeight());
        lineWidth = receipt_llconver.getMeasuredWidth();
        lineHeight = receipt_llconver.getMeasuredHeight();
        moveEnd = -(lineWidth / 2);
        stopTimer();
        runRoll();
    }
    public void setView(LinearLayout line) {
        line.removeAllViews();
        int listsize = noticeList.size();
        for (int i = 0; i < listsize * 2; i++) {
            TextView textView = new TextView(getActivity());
            final int poi = i % listsize;
            if (poi >= listsize) {
                return;
            }
            final String title = noticeList.get(poi).getTitle();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(80, 0, 0, 0);
            textView.setId(i);
            textView.setTextSize(16);
            textView.setTextColor(getResources().getColor(R.color.font2));
            textView.setText(title);
            line.addView(textView, i, params);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*Intent intent = new Intent(getActivity(), NoticeInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", noticeLists.get(poi).getId());
                    intent.putExtras(bundle);
                    startActivity(intent);*/
                    Bundle bundle = new Bundle();
                    bundle.putString("url", noticeList.get(poi).getUrl());
                    //bundle.putString("title","结算费率");
                    jumpToPage(CommonWvActivity.class,bundle);
                }
            });
        }
    }
    public void runRoll() {
        if (timer == null) {
            timer = new Timer();
        }
        if (task == null) {
            task = new MyTask();
            if (roolHandler != null) {
                timer.schedule(task, 0, SPEED);
            }
        }
    }
    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
    }
    private class MyTask extends TimerTask {

        @Override
        public void run() {
            moveSum -= moveSpeed;
            if (moveSum < moveEnd) {
                moveSum = 0;
            } else {
                // roolHandler.sendEmptyMessage(1);
                handler.sendEmptyMessage(MSG_TEXTVIEW_REGRESH);
            }
        }
    }
    @Override
    protected void lazyLoad() {

    }

    @Override
    public void OnBannerClick(int position) {
        if (position==1){
            jumpToPage(ManagePsdActivity.class);
        }else if (position==2){
            jumpToPage(PersonInfoActivity.class);
        }
    }
}
